<template>
  <div class="container">
    <div class="container_main">
      <div class="title_box">
        <h1>
          <img src="@/assets/logo.png" alt="" />
          <span class="title">源力星球智能AI助手</span>
        </h1>
      </div>
      <div class="context_box" style="display: flex; flex-direction: column" ref="ChattingSend">
        <!-- 创建聊天气泡 -->
        <div
          v-for="(item, idx) in combinedMessages"
          :key="idx"
          class="chat_bubble"
          :class="{ my_chatting: item.type === 'user', bot_chatting: item.type === 'bot' }"
          v-html="item.message"
        ></div>
      </div>
      <div class="input_box">
        <input
          v-model="inputValue"
          @keyup.enter="sendMsg"
          style="
            margin-right: 5px;
            height: 50px;
            width: 700px;
            border-radius: 50px;
            border: 1px solid #ccc;
          "
        />

        <el-button
          style="height: 50px; width: 100px; border-radius: 40px; margin-left: 5px"
          @click="sendMsg"
          @keyup.enter="sendMsg"
          >发送</el-button
        >
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick } from "vue";
import { getDeepSeekAPI } from "@/api/deepSeek/deepSeek";
import { marked } from "marked";
import DOMPurify from "dompurify";

// 配置 marked
marked.setOptions({
  breaks: true, // 支持换行符
  gfm: true, // 启用 GitHub Flavored Markdown
});

const ChattingSend = ref<any>(null);
const inputValue = ref<string | null>("");
const userMessages = ref<Array<string>>([]);
const botMessages = ref<Array<string>>([]);

const combinedMessages = computed(() => {
  const messages = [];
  for (let i = 0; i < Math.max(userMessages.value.length, botMessages.value.length); i++) {
    if (i < userMessages.value.length) {
      messages.push({ type: "user", message: userMessages.value[i] });
    }
    if (i < botMessages.value.length) {
      messages.push({ type: "bot", message: botMessages.value[i] });
    }
  }
  return messages;
});

// 滚动到聊天区域底部
const scrollToBottom = () => {
  nextTick(() => {
    if (ChattingSend.value) {
      ChattingSend.value.scrollTop = ChattingSend.value.scrollHeight;
    }
  });
};

const sendMsg = async () => {
  if (!inputValue.value) return;

  userMessages.value.push(inputValue.value);
  botMessages.value.push("");
  const index = botMessages.value.length - 1;

  const temp = inputValue.value;
  inputValue.value = "";

  let accumulatedContent = "";
  try {
    await getDeepSeekAPI(temp, async (chunk) => {
      accumulatedContent += chunk;
      console.log(accumulatedContent);

      try {
        const htmlContent = await marked.parse(accumulatedContent);
        const sanitizedHtml = DOMPurify.sanitize(htmlContent);
        botMessages.value[index] = sanitizedHtml;
        scrollToBottom();
      } catch (parseError) {
        console.error("Marked 解析错误:", parseError);
        const errorMsg = await marked.parse("**解析响应数据时出错，请稍后再试。**");
        botMessages.value[index] = DOMPurify.sanitize(errorMsg);
      }
    });
  } catch (error) {
    console.error("获取数据时出错:", error);
    const errorMsg = await marked.parse("**解析响应数据时出错，请稍后再试。**");

    botMessages.value[index] = DOMPurify.sanitize(errorMsg);
  }
};
</script>

<style lang="scss">
.container {
  text-align: left;
  .container_main {
    position: relative;
    width: 900px;
    height: 700px;
    margin: 0 auto;
    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
    border-radius: 15px;

    .title_box {
      width: 100%;
      border-radius: 15px 15px 0 0;
      height: 70px;
      background-color: #ebeef5;

      h1 {
        line-height: 70px;
        margin-left: 10px;
        img {
          width: 51px;
          height: 40px;
          vertical-align: middle;
        }

        .title {
          font-size: 20px;
          font-weight: 600;
          color: #333;
        }
      }
    }

    .context_box {
      position: relative;
      width: 100%;
      height: 540px;
      overflow-y: auto;
      display: flex;
      flex-direction: column;

      .chat_bubble {
        max-width: 60%;
        padding: 12px 16px;
        border-radius: 20px;
        font-size: 14px;
        line-height: 1.5;
        word-wrap: break-word;
        margin: 10px 0;
        background-color: #f0f0f0;
        color: #333;
        position: relative;
        display: inline-block;
        clear: both;
        white-space: pre-wrap; // 保留换行符，同时允许文本换行
        word-break: break-word; // 长单词或 URL 会在边界处换行
      }

      .my_chatting {
        background-color: #68b4ff;
        align-self: flex-start; /* 靠左对齐 */
        border-bottom-right-radius: 4px;
        margin-right: 10px;
        margin-left: auto; /* 确保右侧有足够的空间 */
      }

      .bot_chatting {
        background-color: #f5f7fa;
        align-self: flex-end; /* 靠右对齐 */
        border-bottom-left-radius: 4px;
        margin-left: 10px;
        margin-right: auto; /* 确保左侧有足够的空间 */
      }

      &::-webkit-scrollbar {
        width: 8px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 4px;
      }
    }

    .input_box {
      width: 900px;
      height: 90px;
      background-color: #f2f6fc;

      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      bottom: 0px;
      border-radius: 0 0 15px 15px;
    }
    .el-input {
      border-radius: 40px;
    }
  }
}
</style>
